package com.hkemmm.shop.utlis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTypeConverter implements Converter<String, Date> {
    private static final String STR_DATE = "yyyy-MM-dd";
    private static final String STR_DATETIME = "yyyy-MM-dd HH:mm:ss";
    private static final String STR_TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSSS";


    @Override
    public Date convert(String s) {
        return toDate(s);
    }

    private Date toDate(String value) {
        Date date = null;

        System.out.println(value);
        if (StringUtils.isNotEmpty(value)) {
            //剔除空格
            String strDateValue = value.trim();
            String strFormat = STR_DATE;

            if (strDateValue.length() <= 10) {

            } else if (strDateValue.length() <= 19) {
                strFormat = STR_DATETIME;
            } else if (strDateValue.length() <= 23) {
                strFormat = STR_TIMESTAMP;
            }


            try {
                SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
                strDateValue = strDateValue.replace("/","-");
                date = sdf.parse(strDateValue);
            } catch (ParseException e) {
                System.out.println("数据类型转化错误:" + e.getMessage());
            }
        }


        return date;
    }
//
//    public static void main(String[] arr){
////        System.out.println(timeStamp2Date("1647755179415"));
//    }

    public Date timeStamp2Date(String time) {
        Long timeLong = Long.parseLong(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date date;
        try {
            date = sdf.parse(sdf.format(timeLong));
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
